package com.dimld.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class Config {
    public static final  Map<String, String> runParams = new HashMap<>();
    private static final Map<String, String> env       = System.getenv();

    /**
     * 获取配置，优先从启动参数获取，无法找到再从配置文件获取，无法找到再从系统变量获取
     *
     * @param name 配置名称
     * @param def  默认值
     * @return 查找到的值
     */
    public static String getConfig(String name, String def) {
        String value = runParams.get(name);
        if (value == null) {
            Properties config = new Properties();
            try {
                String confPath = Tools.getAppPath() + "/conf/config.properties";
                config.load(new FileInputStream(confPath));
                String property = config.getProperty(name);
                if (property == null) {
                    return env.getOrDefault(name, def);
                } else {
                    return property;
                }
            } catch (IOException e) {
                return env.getOrDefault(name, def);
            }
        } else {
            return value;
        }
    }
}